<?php
header ( 'Content-Type: text/html; charset=utf-8' );
ini_set ( 'date.timezone', 'Asia/Shanghai' );
static $site_root="http://www.yaoyoa.com";
static $redirect_page="output.php";
session_start();
//function db_connect($db_ip="localhost",$db_uid="s420448db0",$db_pwd="36mt7jg6",$db_name="s420448db0"){
//function db_connect($db_ip = "localhost", $db_uid = "root", $db_pwd = "!@#$", $db_name = "yaoyoa") {
function db_connect($db_ip = "localhost", $db_uid = "root", $db_pwd = "", $db_name = "yaoyoa") {
	@$result = new mysqli ( $db_ip, $db_uid, $db_pwd, $db_name );
	$error_handle=new error_handle();
	if (mysqli_connect_errno ()||! $result) {
		$error_handle->call_error("sys_0001");
		return false;
	}
	mysqli_query ( $result, "set names 'utf8'" );
	return $result;
}
function db_result_to_array($result) {
	$des_array = array ();
	While ($des_row = $result->fetch_assoc ())
		$des_array[]=$des_row;
//	if ($result && $result->num_rows > 0)
//		for($count = 0; $row = $result->fetch_assoc (); $count ++) //fetch_row  fetch_assoc fetch_array
//			$des_array [] = $row;
	return $des_array;
}
class log{
	//**[get_ip]get the client ip address
	//echo get_ip();//result127.0.0.1
	function get_ip() {
		if (getenv ( "HTTP_CLIENT_IP" ) && strcasecmp ( getenv ( "HTTP_CLIENT_IP" ), "unknown" ))
			$ip = getenv ( "HTTP_CLIENT_IP" );
		else if (getenv ( "HTTP_X_FORWARDED_FOR" ) && strcasecmp ( getenv ( "HTTP_X_FORWARDED_FOR" ), "unknown" ))
			$ip = getenv ( "HTTP_X_FORWARDED_FOR" );
		else if (getenv ( "REMOTE_ADDR" ) && strcasecmp ( getenv ( "REMOTE_ADDR" ), "unknown" ))
			$ip = getenv ( "REMOTE_ADDR" );
		else if (isset ( $_SERVER ['REMOTE_ADDR'] ) && $_SERVER ['REMOTE_ADDR'] && strcasecmp ( $_SERVER ['REMOTE_ADDR'], "unknown" ))
			$ip = $_SERVER ['REMOTE_ADDR'];
		else
			$ip = "unknown";
		return ($ip);
	}
	//**[ip_analyse]translate the ip address into geographic location
	//echo ip_analyse('202.103.24.68');//result本机地址
	function ip_analyse($ip_address) {
		//	list($ip1, $ip2, $ip3,$ip4) = split ('[/.-]', $ip_address);
		//	$longip=$ip1*16777216+$ip2*65536+$ip3*256+$ip4;
		$longip = $ip_address;
		$db = @db_connect ();
		$query = "select * from ip_address Where ip1<='$longip' AND ip2>='$longip' order by ip1 desc limit 0,1";
		$result = $db->query ( $query );
		if (! $result)
			return FALSE;
		else {
			$row = $result->fetch_assoc ();
			return ($row ['address']);
		}
		$result->free ();
		$db->close ();
	}
	function access($analyse_address=FALSE){
		$ip_address=$this->get_ip();
		$address_info=$analyse_address?$this->ip_analyse($ip_address):"";
		$page_dir=$redirect_url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		$refer_page=isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:"";
		$db = @db_connect ();
		$query = "insert into access_log (language,ip_address,browser,visit_time,address_info,page_dir,refer_page) values 
		('".$_SERVER['HTTP_ACCEPT_LANGUAGE']."','".$ip_address."','".$_SERVER['HTTP_USER_AGENT']."','".date("Y-m-d H:i:s")."','$address_info','$page_dir','".$refer_page."')";
		$db->query ( $query );
		return mysqli_insert_id($db);
	}
	function operation(){
		
	}
}
//$ss = new error_handle ( );
//$ss->error_report("login","www.ddd","yao");
class error_handle{
	function call_error($error_id="",$target_url="",$parameter=TRUE){
		global $redirect_page;
		if ($parameter)
			$redirect_url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		else
			$redirect_url="http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
		if ($target_url!="")$redirect_url=$target_url;
		if (strpos($redirect_url,$redirect_page))
			$redirect_url="default.php";
		$redirect_url=urlencode(($redirect_url));
		global $site_root;
		header( "Location: $site_root/$redirect_page?error_id=".$error_id."&redirect_url=".$redirect_url );
		die();
	}
	function get_error_info($error_id=""){
		if ($error_id=="")return FALSE;
		$conn = @db_connect ();
		$sql_str = "select title,content,error_type from error_definition where error_id='$error_id'";
		$result = $conn->query ( $sql_str );
		if (! $result || $result->num_rows == 0)
			return FALSE;
		else
			return db_result_to_array($result);
	}
	function error_report($error_type="",$error_link,$relate_uid,$ip_analyse=FALSE){
		$data_manage=new data_manage();
		$log_access=new log();
		if($ip_analyse){
			$access_id=$log_access->access(TRUE);
		}else
			$access_id=$log_access->access();
		$data_array=array("error_type"=>$error_type,"error_link"=>$error_link,"relate_uid"=>$relate_uid,"update_time"=>date("Y-m-d H:i:s"),"access_id"=>$access_id);
		$data_manage->update_array($data_array,"error_report",$update_type="insert");
	}
}
// $dd=new authorize();
// print_r( $dd->check_user('wong'));
class authorize{
	function check_user($name){
		$data=new data();
		$a=$data->preview(array('id','uid'),'member',null,null,"user_name='$name' and ( group_id='mate' or group_id='admin') and status<>0");
//		$log=new log();
//		$access_id=$log->access();
		if ($a && $a->num_rows == 1){
			$result=$a->fetch_assoc ();
			$result['type']='user';
			return $result;
		}else{
			return false;
		}
	}
	function login($uid,$pwd){
		
	}
}
//$dd=new data();
//$dd->update(array(0=>array("id"=>3,"data_value"=>"dddffdd","data_type"=>"accessory","relate_id"=>35)),'relate_data',"insert");
//$dd->get('relate_data',13);
//$dd->preview(array('id','name'));
class data{
	private function get_max_dim($v_dim)
	{
	    if(!is_array($v_dim)) return 0;
	    else
	    {
	        $max1 = 0;
	        foreach($v_dim as $item1)
	        {
	            $t1 = $this->get_max_dim($item1);
	            if( $t1 > $max1) $max1 = $t1;
	        }
	        return $max1 + 1;
	    }
	}
	function tag($tag_array=null,$page_no = 1, $page_size = 10){
		if (is_array($tag_array)) {
			$sql_str = "select id,title,left(content,200) as content,length(content) as content_len,catalog_id,write_time from article where display_state = 1";
			$sql_str_temp="";
			foreach ($tag_array as $val1)
				$sql_str_temp.=" or key_word like '%$val1%'";
			$sql_str.=" and (".substr($sql_str_temp,3).")";
			$sql_str .= " limit " . ($page_no - 1) * $page_size . "," . $page_size;
		}
		$conn = @db_connect ();
		$result = $conn->query ( $sql_str );
		return $result;
	}
	function preview($column_array=FALSE,$table_name = "article",$page_no = 1, $record_count = 10, $condition_str='') {
		if (! is_numeric ( $record_count ) && ! $record_count == "all")
			$record_count = 10;
		if (! is_numeric ( $page_no ) )
			$page_no = 1;
			if ($table_name=="")$table_name = "article";
		if ($column_array!==FALSE){
			$column_str='';
			foreach ($column_array as $val){
				$column_str.="`$val`,";
			}
			$column_str=substr($column_str,0,strlen($column_str)-1);
		}else
			$column_str="*";
		$sql_str = "select $column_str from `$table_name`";

		if ($condition_str!==''){
			$sql_str.=" where $condition_str";
		}
		$sql_str .= " limit " . ($page_no - 1) * $record_count . "," . $record_count;
//		die($sql_str);
		$conn = @db_connect ();
		$result = $conn->query ( $sql_str );
		//echo $result->num_rows; //获取记录数
		if (! $result || $result->num_rows == 0){
			return false; 
		}
		else
			return $result;
	}
	function update($data_array=FALSE,$table_name,$update_type="insert"){
		if ($data_array!==FALSE){
			$data_dim=$this->get_max_dim($data_array);
			if ($data_dim==1){
				if ($update_type=="insert")
					$sql_relate_data="insert into $table_name set ";
				elseif ($update_type=="update")
					$sql_relate_data="update $table_name set ";
				foreach ($data_array as $key1=>$val1){
					if ($key1!="id")
						$sql_relate_data.=$key1."='".$val1."',";
					else
						$update_id=$val1;
				}
				$sql_relate_data=substr($sql_relate_data,0,strlen($sql_relate_data)-1);
				if ($update_type=="update")
					$sql_relate_data.=" where id=".$update_id;
				if ($sql_relate_data){
					$conn = @db_connect ();
					$result=$conn->query ($sql_relate_data);
					if (!$result)
						return "db_0001";
					else
						return mysqli_insert_id($conn);
				}
			}
			elseif ($data_dim==2){
				foreach ($data_array as $val2){
					$update_id=NULL;
					if ($update_type=="insert")
						$sql_relate_data="insert into $table_name set ";
					elseif ($update_type=="update")
						$sql_relate_data="update $table_name set ";
					foreach ($val2 as $key3=>$val3){
						if ($key3!="id")
							$sql_relate_data.=$key3."='".$val3."',";
						else
							$update_id=$val3;
					}
					$sql_relate_data=substr($sql_relate_data,0,strlen($sql_relate_data)-1);
					if ($update_type=="update"&&isset($update_id))
						$sql_relate_data.=" where id=".$update_id;
					elseif ($update_type=="update"&&!isset($update_id))
						$sql_relate_data=FALSE;
					if ($sql_relate_data){
						$conn = @db_connect ();
						if (!@$conn->query ($sql_relate_data))return "db_0001";
					}
				}
			}
		}
		else
			return FALSE;
	}
	//**[delete_record]
	////delete_record('weather',2);//delete the record
	function delete($table_name, $record_id) {
		if ($table_name != '' && is_numeric( $record_id )) {
			$conn = @db_connect ();
			$sql_str = "delete from $table_name where id=$record_id";
			$conn->query ( $sql_str );
		}
	}
	function get($table_name,$record_id,$column_array=FALSE){
		if ($table_name == '' || !is_numeric( $record_id ))return '传递参数中不包含表名';
		$column_str='';
		if ($column_array!==FALSE){
			foreach ($column_array as $val){
				$column_str.="`$val`,";
			}
			$column_str=substr($column_str,0,strlen($column_str)-1);
		}else
			$column_str="*";
		$conn = @db_connect ();
		$sql_str = "select $column_str from `$table_name` where id=$record_id";
		$result=$conn->query ( $sql_str );
		if (! $result || $result->num_rows == 0)
			return '没有符合条件的记录'; 
		else
			return ($result);
	}
	function find($table_name,$relation,$column_array=FALSE){
		if ($table_name == '' || !is_numeric( $record_id ))return '传递参数中不包含表名';
		if ($column_array!==FALSE){
			foreach ($column_array as $val){
				$column_str.="`$val`,";
			}
			$column_str=substr($column_str,0,strlen($column_str)-1);
		}else
			$column_str="*";
		if (is_array($relation)){
			
		}
		$conn = @db_connect ();
		$sql_str = "select $column_str from `$table_name` where id=$record_id";
		$result=$conn->query ( $sql_str );
		if (! $result || $result->num_rows == 0)
			return '没有符合条件的记录'; 
		else
			return ($result);
	}
}
/*class image{
	function resize(){
$src_img = "/../file/3.gif";

$dst_w = 300;

$dst_h = 200;


list($src_w,$src_h)=getimagesize($src_img);  // 获取原图尺寸



$dst_scale = $dst_h/$dst_w; //目标图像长宽比

$src_scale = $src_h/$src_w; // 原图长宽比



if($src_scale>=$dst_scale){  // 过高

$w = intval($src_w);

$h = intval($dst_scale*$w);



$x = 0;

$y = ($src_h - $h)/3;

}

else{ // 过宽

$h = intval($src_h);

$w = intval($h/$dst_scale);



$x = ($src_w - $w)/2;

$y = 0;

}



// 剪裁

//$source=imagecreatefromjpeg($src_img);
$data=getimagesize($src_img);
//print_r($data);
//die();
switch ($data[2]) {
case 1:
$source=@ImageCreateFromGIF($src_img);
break;
case 2:
$source=@ImageCreateFromJPEG($src_img);
break;
case 3:
$source=@ImageCreateFromPNG($src_img);
break;
} 
$croped=imagecreatetruecolor($w, $h);

imagecopy($croped,$source,0,0,$x,$y,$src_w,$src_h);



// 缩放

$scale = $dst_w/$w;

$target = imagecreatetruecolor($dst_w, $dst_h);

$final_w = intval($w*$scale);

$final_h = intval($h*$scale);
 
imagecopyresampled($target,$croped,0,0,0,0,$final_w,$final_h,$w,$h);



// 保存

$timestamp = time();

imagejpeg($target, "$timestamp.jpg");

imagedestroy($target);
	}	
}

*/
//$p=new CImage("/../file/04043266189300.gif");        //创建一个图片处理对象
//$p->thumb("3.gif",50);    //生成缩略图 限制尺寸为300,保存为thumb.jpg
//$p->rotate("rt.jpg",90);        //旋转90度，并保存为rt.jpg,类似地，你可以将90换成180,270进行旋转
//$p->rotate_h("h.jpg");        //水平翻转
//$p->rotate_v("v.jpg");        //垂直翻转
class CImage{
    var $src_image;
    var $width;
    var $height;
    var $image_type;
    var $img;
    var $src_x;
    var $src_y;
   
    function __construct($image_file)
    {
        $info=GetImageSize($image_file);
        $this->src_image=$image_file;
        $this->width=$info[0];
        $this->height=$info[1];
        
        switch($info[2])
        {
            case 1:
                $this->image_type="gif";
                break;
            case 2:
                $this->image_type="jpeg";
                break;
            case 3:
                $this->image_type="png";
                break;
            default:
                return false;
                //echo("Unsurport Image type.");
                break;
        }    //swith end
        //echo "ok";
        $new_function='ImageCreateFrom'.ucfirst($this->image_type);
        $this->img=$new_function($this->src_image);
        $this->src_x=ImageSX($this->img);
        $this->src_y=ImageSY($this->img);
    }
    function thumb($image_dist,$x)        //$x为新图的限制边的尺寸
    {        
        $src_x=ImageSX($this->img);
        $src_y=ImageSY($this->img);
        $scale=min($x/$src_x,$x/$src_y);
   
        if($scale<1)
        {
            $new_x=floor($scale*$src_x);
            $new_y=floor($scale*$src_y);
            $img_tmp=ImageCreateTrueColor($new_x,$new_y);    //set the size of Canvas for the new Image
            ImageCopyResampled($img_tmp,$this->img,0,0,0,0,$new_x,$new_y,$src_x,$src_y);    //Resampled
            //ImageDestroy($this->img);
            $new_function="Image".ucfirst($this->image_type);

            return $new_function($img_tmp,$image_dist);
        }
    }    //  thumb end
    function destroy(){
    	ImageDestroy($this->img);
    }
   
 //给图片生成文字水印
    function image_press($image_dist,$str,$font="simkai.ttf") { 
        $str=iconv("GB2312","utf-8",$str);            
        $blue=ImageColorAllocate($this->img,90,255,255);
        $white=ImageColorAllocate($this->img,255,0,0);
        ImageTTFText($this->img,20,0,$this->src_x/2/2,$this->src_y-80,$white,$font,$str);
        $new_function="Image".ucfirst($this->image_type);
        return $new_function($this->img,$image_dist);        
    }

    function rotate($image_dist,$angle)
    {
        $img_tmp=null;
        $new_function="Image".ucfirst($this->image_type);
        if(($angle!=90)&&($angle!=180)&&($angle!=270))
        {
            echo("Un-valid angle on calling CImage::rotate(\$image_dist,\$angle) .<p>The valid angle must be 90 or 180 or 270.");
            return false;
        }

        if(($angle==90)||($angle==270))
        {
            $img_tmp=ImageCreateTrueColor($this->src_y,$this->src_x);
        }
        else
        {
            $img_tmp=ImageCreateTrueColor($this->src_x,$this->src_y);
        }
        
        switch($angle)
        {
            case 90:
                for($i=0;$i<$this->src_x;$i++)
                {
                    for($j=0;$j<$this->src_y;$j++)
                    {
                        ImageSetPixel($img_tmp,$this->src_y-$j-1,$i,ImageColorAt($this->img,$i,$j));   
                    }
                }   
                return $new_function($img_tmp,$image_dist);
                break;

            case 180:
                for($i=0;$i<$this->src_x;$i++)
                {
                    for($j=0;$j<$this->src_y;$j++)
                    {
                        ImageSetPixel($img_tmp,$this->src_x-$i-1,$this->src_y-$j-1,ImageColorAt($this->img,$i,$j));   
                    }
                }
                return $new_function($img_tmp,$image_dist);
                break;

            case 270:
                for($i=0;$i<$this->src_x;$i++)
                {
                    for($j=0;$j<$this->src_y;$j++)
                    {
                        ImageSetPixel($img_tmp,$j,$this->src_x-$i-1,ImageColorAt($this->img,$i,$j));   
                    }
                }
                return $new_function($img_tmp,$image_dist);
                break;
        }    //end switch
        
    }        //end rotate
   
    function rotate_h($image_dist)
    {
        $new_function="Image".ucfirst($this->image_type);
        $img_tmp=ImageCreateTrueColor($this->src_x,$this->src_y);
        ImageCopyResampled($img_tmp,$this->img,0,0,$this->src_x-1,0,$this->src_x,$this->src_y,-$this->src_x,$this->src_y); //水平翻转
        return    $new_function($img_tmp,$image_dist);   
    }
   
    function rotate_v($image_dist)
    {
    $new_function="Image".ucfirst($this->image_type);
    $img_tmp=ImageCreateTrueColor($this->src_x,$this->src_y);
    ImageCopyResampled($img_tmp,$this->img,0,0,0,$this->src_y-1,$this->src_x,$this->src_y,$this->src_x,-$this->src_y);
    return $new_function($img_tmp,$image_dist);
    }   
}    //end CImage 
//
//$encrypt=new encrypt();
//$string = "9"; 
// 
//// encrypt $string, and store it in $enc_text
//$enc_text = $encrypt->encrypt($string); 
// 
//// decrypt the encrypted text $enc_text, and store it in $dec_text
//$dec_text = $encrypt->decrypt($enc_text); 
// 
//print "加密的 text : $enc_text" ;
//print "encode加密的 text : ".urlencode($enc_text) ;
//print "解密的 text : $dec_text ";
class encrypt{
// 说明：PHP 写的加密函数,支持私人密钥
// 整理：http://www.CodeBit.cn
    var $key;
	
    function __construct($key='')
    {
    	if ($key!=='')
			$this->key=$key;
		else
			$this->key='yk8274@2f4';
    }
	function keyED($txt)
	{
	    $encrypt_key = md5($this->key);
	    $ctr=0;
	    $tmp = "";
	    for ($i=0;$i<strlen($txt);$i++)
	    {
	        if ($ctr==strlen($encrypt_key)) $ctr=0;
	        $tmp.= substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1);
	        $ctr++;
	    }
	    return $tmp;
	} 
	 
	function encrypt($txt)
	{
	    srand((double)microtime()*1000000);
	    $encrypt_key = md5(rand(0,32000));
	    $ctr=0;
	    $tmp = "";
	    for ($i=0;$i<strlen($txt);$i++)
	    {
	        if ($ctr==strlen($encrypt_key)) $ctr=0;
	        $tmp.= substr($encrypt_key,$ctr,1) . (substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1));
	        $ctr++;
	    }
	    return $this->keyED($tmp);
	} 
	 
	function decrypt($txt)
	{
	    $txt = $this->keyED($txt);
	    $tmp = "";
	    for ($i=0;$i<strlen($txt);$i++)
	    {
	        $md5 = substr($txt,$i,1);
	        $i++;
	        $tmp.= (substr($txt,$i,1) ^ $md5);
	    }
	    return $tmp;
	}
}
